using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using deckAnalyser.Controls;
using deckAnalyser.Support;

namespace deckAnalyser.Controls
{
  public partial class CollectionGridControl : UserControl
  {
    public CollectionGridControl()
    {
      InitializeComponent();
      FilterType = "Name";
      dataGridView.KeyDown += new KeyEventHandler(dataGridView_KeyDown);
      dataGridView.RowEnter += new DataGridViewCellEventHandler(dataGridView_RowEnter);

    }

    private void dataGridView_RowEnter(object sender, DataGridViewCellEventArgs e)
    {
      UpdateCardDetailsControl(e.RowIndex);
    }


    private void dataGridView_KeyDown(object sender, KeyEventArgs e)
    {
      if (dataGridView.CurrentCell != null)
      {
        DataGridViewCell countCell = dataGridView["Count", dataGridView.CurrentCell.RowIndex];
        DataGridViewCell foilsCell = dataGridView["Foils", dataGridView.CurrentCell.RowIndex];
        DataGridViewCell nameCell = dataGridView["Card Name", dataGridView.CurrentCell.RowIndex];
        DataGridViewCell setCell = dataGridView["Set Name", dataGridView.CurrentCell.RowIndex];
        DataGridViewCell actionCell = dataGridView["Action", dataGridView.CurrentCell.RowIndex];

        if (e.KeyCode == Keys.Oemplus && !e.Shift)
        {
          countCell.Value = (Int64)countCell.Value + 1;
          e.Handled = true;
        }

        if (e.KeyCode == Keys.OemMinus && !e.Shift)
        {
          if ((Int64)countCell.Value > 0)
            countCell.Value = (Int64)countCell.Value - 1;
          e.Handled = true;
        }

        if (e.KeyCode == Keys.Oemplus && e.Shift)
        {
          foilsCell.Value = (Int64)foilsCell.Value + 1;
          e.Handled = true;
        }

        if (e.KeyCode == Keys.OemMinus && e.Shift)
        {
          if ((Int64)foilsCell.Value > 0)
            foilsCell.Value = (Int64)foilsCell.Value - 1;
          e.Handled = true;
        }

        if (e.Handled == true)
        {
          String cardName = ((String)(nameCell.Value));
          String setName = ((String)(setCell.Value));
          String action = (String)(actionCell.Value);
          long cnt = (Int64)countCell.Value;
          long fcnt = (Int64)foilsCell.Value;

          if (action == "I")
          {
            if (cnt != 0 || fcnt != 0)
            {
              DBWrapper.ExecuteNonQuery
                  (
                      "insert into collections.collectioncards " +
                      "(name,cardname,setname,cnt,fcnt) " +
                      "values (\"" + CollectionName + "\",\"" + cardName + "\",\"" + setName + "\",\"" + cnt + "\",\"" + fcnt + "\")"
                  );
              dataGridView["Action", dataGridView.CurrentCell.RowIndex].Value = "U";
            }
          }
          else
          {
            if (cnt == 0 && fcnt == 0)
            {
              DBWrapper.ExecuteNonQuery
                  (
                      "delete from  collections.collectioncards " +
                      "where name=\"" + CollectionName + "\" and cardname=\"" + cardName + "\" and setname=\"" + setName + "\""
                  );
              dataGridView["Action", dataGridView.CurrentCell.RowIndex].Value = "I";
            }
            else
            {
              DBWrapper.ExecuteNonQuery
              (
                  "update collections.collectioncards " +
                  "set cnt='" + cnt + "',fcnt='" + fcnt + "' " +
                  "where name=\"" + CollectionName + "\" and cardname=\"" + cardName + "\" and setname=\"" + setName + "\""
              );

            }
          }



        }
        else
        {
          if (Char.IsLetterOrDigit((char)e.KeyValue) || e.KeyCode == Keys.Space)
          {
            if (e.Shift)
              FilterValue = FilterValue + (Char)e.KeyValue;
            else
              FilterValue = FilterValue + ((Char)e.KeyValue).ToString().ToLower();
          }
          else if (e.KeyCode == Keys.Back)
          {
            if (!String.IsNullOrEmpty(FilterValue))
            {
              FilterValue = FilterValue.Remove(FilterValue.Length - 1, 1);
            }
          }
          else if ((char)e.KeyValue=='\'')
          {
            FilterValue = FilterValue + (Char)e.KeyValue;
          }
          else if (e.KeyCode == Keys.Enter)
          {
            FilterValue = "";
          }
        }
      }
      else
      {
        if (e.KeyCode == Keys.Back)
        {
          if (!String.IsNullOrEmpty(FilterValue))
          {
            FilterValue = FilterValue.Remove(FilterValue.Length - 1, 1);
          }
        }
        else if (e.KeyCode == Keys.Enter)
        {
          FilterValue = "";
        }
      }
    }

    private BindingSource bs = new BindingSource();
    private void LoadData()
    {
      if (DBWrapper.IsOpen)
      {
        DataTable dt = DBWrapper.GetDataTable
        (
            "select  x.name                as 'Card Name'" +
            "       ,x.setname             as 'Set Name'" +
            "       ,ifnull(lc.cnt,0)      as 'Count'" +
            "       ,ifnull(lc.fcnt,0)     as 'Foils'" +
            "       ,x.cost                as 'Cost'" +
            "       ,x.rarity              as 'Rarity'" +
            "       ,x.text                 as 'Text'" +
            "       ,x.type                as 'Type'" +
            "       ,case 1 when (lc.cnt>=0 or lc.fcnt>=0) " +
            "        then 'U' else 'I' end as 'Action' " +
            "from    (select * from master.cards c join master.setcards sc on sc.cardname = c.name) x " +
            " left outer join collections.collectioncards lc " +
            "on      x.name       = lc.cardname " +
            "and     x.setname  = lc.setname " +
            "and     lc.name      = '" + CollectionName + "'"
        );


        bs.DataSource = dt;
        bs.Filter = null;

        dataGridView.DataSource = bs;
        for (int i = 0; i < dataGridView.Columns.Count; i++)
        {
          if (
              dataGridView.Columns[i].Name == "Cost" ||
              dataGridView.Columns[i].Name == "Text" ||
              dataGridView.Columns[i].Name == "Rarity" ||
              dataGridView.Columns[i].Name == "Action" ||
              dataGridView.Columns[i].Name == "Type"
             )
            dataGridView.Columns[i].Visible = false;
        }

        dataGridView.Columns["Card Name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        dataGridView.Columns["Set Name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        dataGridView.Columns["Count"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
        dataGridView.Columns["Foils"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;


        for (int i = 0; i < dt.Columns.Count; i++)
        {
          dataGridView.Columns[i].ReadOnly = true;
        }

        UpdateCardDetailsControl();
      }
    }

    private void UpdateData()
    {
      LoadData();
      toolStripStatusLabel1.Text = "Collection [" + CollectionName + "]";
    }


    private String collectionName = "Default";
    public String CollectionName
    {
      get { return collectionName; }
      set { collectionName = value; UpdateData(); }
    }


    private void setFilter()
    {
      if (String.IsNullOrEmpty(FilterValue))
      {
        bs.Filter = null;
      }
      else
      {
        string f = "";
        if (FilterType == "Name") f = "Card Name";
        if (FilterType == "Set") f = "Set Name";
        if (FilterType == "Text") f = "Text";


        bs.Filter = "[" + f + "] like '%" + FilterValue + "%'";
      }

      toolStripStatusLabel2.Text = "[" + FilterValue + "]";
    }


    private string filterValue = "";
    public string FilterValue
    {
      set { filterValue = value; setFilter(); }
      get { return filterValue; }
    }

    private string filterType = "";
    public string FilterType
    {
      set { filterType = value; toolStripStatusLabel3.Text = "[" + value + "]"; setFilter(); }
      get { return filterType; }
    }


    private CardDetailsControl cardDetailsControl = null;
    public CardDetailsControl CardDetailsControl
    {
      get { return cardDetailsControl; }
      set { cardDetailsControl = value; UpdateCardDetailsControl(); }
    }


    private void UpdateCardDetailsControl(int row)
    {
      if (cardDetailsControl != null)
      {
        cardDetailsControl.CardName = (String)dataGridView["Card Name", row].Value;
        cardDetailsControl.CardCost = (String)dataGridView["Cost", row].Value;
        cardDetailsControl.CardType = (String)dataGridView["Type", row].Value;
        cardDetailsControl.CardSet = (String)dataGridView["Set Name", row].Value;
        cardDetailsControl.CardRarity = (String)dataGridView["Rarity", row].Value;
        cardDetailsControl.CardText = (String)dataGridView["Text", row].Value;
      }
    }


    private void UpdateCardDetailsControl()
    {
      if (dataGridView.CurrentRow != null)
      {
        int row = dataGridView.CurrentRow.Index;
        UpdateCardDetailsControl(row);
      }
    }

    private void toolStripMenuItem2_Click(object sender, EventArgs e)
    {
      FilterType = "Name";
    }

    private void toolStripMenuItem1_Click(object sender, EventArgs e)
    {
      FilterType = "Set";
    }

    private void toolStripMenuItem3_Click(object sender, EventArgs e)
    {
      FilterType = "Text";
    }

    private void dataGridView_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
    {
      //DataGridView dgv = (DataGridView)sender;

      //if ((e.RowIndex % 2) == 0)
      //{
      //  dgv.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
      //  dgv.Rows[e.RowIndex].DefaultCellStyle.SelectionForeColor = Color.Red;
      //}
    }


  }
}
